
var base_query_url = '',
    csacr_base_query_uri = '/google-dsapi-svc/addama/datasources/csacr',
    tcga_base_query_uri = '/google-dsapi-svc/addama/datasources/tcga',
    network_uri = '/v_crad_feature_networks/query',
    feature_uri = '/v_crad_features/query',
    patient_uri = '/v_crad_patients/query',
    feature_data_uri = '/v_crad_patient_values/query',
    query_uri = '/query',
    linear_args = {features : null},
    parsed_data = {network : null,unlocated : null},
    responses = {network : null},
    patients = {data : null},
    annotations = {'chrom_leng': null,'patients': null},
    args = {features : null,unlocated_features:null};

buildGQLQuery = function(args) {
    var source =args['source'],label=args['label'],chr=args['chr'],start=args['start'],stop=args['stop'],importance=args['importance'],
            order=args['order'],limit=args['limit'];
      var query = 'select id, chr, start, end, `rank`, `type`, `source`, `weight`,`label`';
    var whst = ' where',
    where = whst;

    if (source != '' && source != '*') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'source = \'' +source+ '\'';
    }

    if (label != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += '`label` = \'' +label+ '\'';
    }

    if (chr != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'chr = \'' +chr+'\'';
    }
    if (start != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'start >= ' +start;
    }
    if (stop != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'end <= ' +stop;
    }

    query += (where.length > whst.length ? where : '');
    query += ' order by '+order +' DESC';

    query += ' limit '+limit + 'label `label` \'value\'';

    return query;
};

function loadFeatureData(link,callback) {
    patients = {data : null};

    var timer =  new vq.utils.SyncDatasources(4000,40,callback,patients);
    timer.start_poll();

    var query_str = 'select f1id, f2id, f1alias, f1values, f2alias, f2values ' +
            'where f1id  = ' + link.sourceNode.id + ' and f2id = ' + link.targetNode.id + ' limit 1';
    var patient_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + feature_data_uri);
    patient_query.setQuery(query_str);

    function patientQueryHandle(response) {
          if (!response.isError()) {
              patients['data'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
          }  else {
              console.log('Patient Data request failed');
          }
    }

    patient_query.send(patientQueryHandle);

}

function loadAnnotations(callback) {

    annotations = {'chrom_leng': null,'patients': null};

    var timer = new vq.utils.SyncDatasources(2000,40,callback,annotations);
    timer.start_poll();
    var chrom_query = new google.visualization.Query(base_query_url + csacr_base_query_uri + '/chrom_info' + query_uri);
    chrom_query.setQuery('select chr_name, chr_length');
    function handleChromInfoQuery(response) {
        annotations['chrom_leng'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
    }
    chrom_query.send(handleChromInfoQuery);

    var patient_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + patient_uri);
    patient_query.setQuery('limit 1');

    function patientQueryHandle(response) {
          if (!response.isError()) {
              annotations['patients'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable())[0]['barcode'].split(':');
          }
    }

    patient_query.send(patientQueryHandle);

}


function loadData(query,callback) {

    args = {features : null,unlocated_features:null};

    var timer = new vq.utils.SyncDatasources(2000,40,callback,args);
    timer.start_poll();

    var rank_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + feature_uri);
    rank_query.setQuery(query);

    function handleLinkQuery(response) {
        args['features'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
        args['unlocated_features'] = vq.utils.VisUtils.clone(args['features']).filter(function(feature) {
            return feature.chr =='';
        })
    }
    rank_query.send(handleLinkQuery);

}



function parseNetwork(query_params,callback) {

    parsed_data = {network : null,unlocated : null};
    var timer = new vq.utils.SyncDatasources(4000,40,callback,parsed_data);

    timer.start_poll();

    var whole_net = responses['network'].map(function(row) {
        var node1 = row.alias1.split(':');
        var node2 = row.alias2.split(':');
           return {node1: {id : row.id1, source : node1[1], label : node1[2], chr : node1[3].slice(3),
               start: parseInt(node1[4]), end:node1[5] != '' ? parseInt(node1[5]) : ''},
            node2: {id : row.id2, source : node2[1], label : node2[2], chr : node2[3].slice(3),
                start: parseInt(node2[4]), end:node2[5] != '' ? parseInt(node2[5]) : ''},
            importance : row.importance, correlation:row.correlation};
    }
            );
        var located_responses = whole_net.filter(function(feature) {
        return feature.node1.chr != '' && feature.node2.chr != '';});

        var unlocated_responses =  whole_net.filter(function(feature) {
        return feature.node1.chr == '' || feature.node2.chr == '';});


    parsed_data['network'] = located_responses;
    parsed_data['unlocated'] = unlocated_responses;
}


function loadNetworkData(query_params,callback) {
    response_check={data : null};

     var importance =query_params['importance'],
    correlation =query_params['correlation'],
    target_source = query_params['target_source'],
    target_chr = query_params['target_chr'];

    if (importance.length < 1) importance = 0;
    if (correlation.length < 1) correlation = 0;

    var rank_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + network_uri);
    var feature_ids = vq.utils.VisUtils.clone(args['features']).map(function(feature) { return feature.id;});

    function handleNetworkQuery(response) {
          response_check['data'] = 1;
          responses = {network : null};
      var timer = new vq.utils.SyncDatasources(4000,40,function() {parseNetwork(query_params,callback);},responses);
      timer.start_poll();
          responses['network'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
      }

    var or_statement = feature_ids.map(function(id) { return 'feature1id = ' + id;}).join(' or '),
        source_statement =  (target_source.length > 1 ? 'alias2 contains \':' + target_source + ':\'' : ''),
        chr_statement =  (target_chr.length > 0 ? 'alias2 contains \':chr' + target_chr + ':\'' : '');

        rank_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + network_uri);
        rank_query.setQuery('select feature1id, feature2id, alias1, alias2, importance, correlation where importance >= '+
                importance + ' and correlation >= ' + correlation +' and ' +
                (source_statement.length > 0 ? source_statement + ' and ' : '') +
                 (chr_statement.length > 0 ? chr_statement + ' and ' : '') +
                '(' + or_statement + ') order by importance DESC label feature1id \'id1\', feature2id \'id2\'');
    var timer = new vq.utils.SyncDatasources(10000,40,function() {return null;},response_check);
    timer.start_poll();
        rank_query.send(handleNetworkQuery);
}